#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
简化版 Joycon 手柄读取器
只包含最基本的连接检测和参数读取功能

Author: Assistant
Date: 2024-12-19
"""

import pygame
import time
import sys
import subprocess
import re
from typing import Dict, List, Optional

class SimpleJoyconReader:
    """简化的 Joycon 手柄读取器"""
    
    def __init__(self):
        """初始化读取器"""
        self.joysticks = []
        self.connected = False
        
        # 初始化 pygame
        pygame.init()
        pygame.joystick.init()
        
        # 检查连接
        self._check_connection()
    
    def _check_connection(self):
        """检查 Joycon 连接状态"""
        print("正在检查 Joycon 连接状态...")
        
        # 方法1: 检查蓝牙设备
        try:
            result = subprocess.run(['bluetoothctl', 'devices'], 
                                  capture_output=True, text=True, timeout=5)
            
            joycon_found = False
            for line in result.stdout.split('\n'):
                if 'joy-con' in line.lower() or 'nintendo' in line.lower():
                    print(f"发现 Joycon 设备: {line.strip()}")
                    joycon_found = True
            
            if not joycon_found:
                print("未在蓝牙设备中发现 Joycon")
        except Exception as e:
            print(f"检查蓝牙设备失败: {e}")
        
        # 方法2: 检查 pygame 手柄
        joystick_count = pygame.joystick.get_count()
        print(f"检测到 {joystick_count} 个手柄设备")
        
        if joystick_count == 0:
            print("错误: 未检测到任何手柄设备")
            print("请确保 Joycon 已正确连接")
            return
        
        # 初始化手柄
        for i in range(joystick_count):
            joystick = pygame.joystick.Joystick(i)
            joystick.init()
            
            name = joystick.get_name()
            print(f"手柄 {i}: {name}")
            print(f"  轴数量: {joystick.get_numaxes()}")
            print(f"  按钮数量: {joystick.get_numbuttons()}")
            
            self.joysticks.append(joystick)
        
        self.connected = True
        print("Joycon 连接检查完成")
    
    def read_inputs(self) -> Optional[Dict]:
        """读取手柄输入"""
        if not self.connected or not self.joysticks:
            return None
        
        # 处理 pygame 事件
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                return None
        
        data = {
            'buttons': {},
            'axes': {},
            'connected': self.connected
        }
        
        # 读取每个手柄的输入
        for joystick_id, joystick in enumerate(self.joysticks):
            # 读取按钮
            for i in range(joystick.get_numbuttons()):
                button_pressed = joystick.get_button(i)
                if button_pressed:
                    data['buttons'][f'joycon_{joystick_id}_button_{i}'] = True
            
            # 读取摇杆轴
            for i in range(joystick.get_numaxes()):
                axis_value = joystick.get_axis(i)
                if abs(axis_value) > 0.1:  # 只记录有意义的输入
                    data['axes'][f'joycon_{joystick_id}_axis_{i}'] = axis_value
        
        return data
    
    def print_status(self, data: Dict):
        """打印状态信息"""
        if not data:
            return False
        
        print("\n" + "="*50)
        print("Joycon 状态")
        print("="*50)
        
        if data['connected']:
            print("✅ 连接状态: 已连接")
        else:
            print("❌ 连接状态: 未连接")
            return False
        
        # 显示按钮状态
        if data['buttons']:
            print("🔘 按下的按钮:")
            for button, pressed in data['buttons'].items():
                if pressed:
                    print(f"  - {button}")
        else:
            print("🔘 按钮: 无按下")
        
        # 显示摇杆状态
        if data['axes']:
            print("🎮 摇杆输入:")
            for axis, value in data['axes'].items():
                print(f"  - {axis}: {value:.3f}")
        else:
            print("🎮 摇杆: 无输入")
        
        return True
    
    def run(self, update_rate: float = 10.0):
        """运行主循环"""
        print("启动简化版 Joycon 读取器...")
        print("按 Ctrl+C 退出程序")
        
        try:
            while True:
                data = self.read_inputs()
                if not self.print_status(data):
                    break
                time.sleep(1.0 / update_rate)
                
        except KeyboardInterrupt:
            print("\n程序已退出")
        finally:
            pygame.quit()

def main():
    """主函数"""
    print("简化版 Joycon 手柄读取器")
    print("="*50)
    
    try:
        # 创建读取器
        reader = SimpleJoyconReader()
        
        # 运行主循环
        reader.run()
        
    except Exception as e:
        print(f"错误: {e}")
        print("\n故障排除:")
        print("1. 确保 Joycon 已通过蓝牙连接")
        print("2. 检查蓝牙是否已启用")
        print("3. 尝试重新配对手柄")
        print("4. 在 Linux 上可能需要:")
        print("   sudo modprobe hid-nintendo")

if __name__ == "__main__":
    main() 